/*
	* --------------------------------------------------------------------------
	*
  * Copyright 2011 Matthew West T/A Developer City
	*
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
	*
  *   http://www.apache.org/licenses/LICENSE-2.0
	*
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  *
  * --------------------------------------------------------------------------
*/

// Listen for an incoming message
self.addEventListener('message', function(e) {
  var data = e.data;
  var historyItems = data.historyItems;
  
  totalPageViews = 0;
  
  allDomains = [];
	rootDomains = [];
	uniquePages = [];
  
  allDomains = historyItems;
	// For each history item, get details on all visits.
	for (var i = 0; i < historyItems.length; ++i) {
		var url = historyItems[i].url;
		var visitCount = historyItems[i].visitCount;

		// Get the base url
		var baseURL = getBaseURL(url);

		// Add the domain to the rootDomains array
		// This function first checks that the domain is not already present
		addRootDomain(baseURL, visitCount);

		// Add the page to the unique pages arrays
		addUniquePage(url);

		totalPageViews += visitCount;
	}

	// Find the top ten websites
	sortRootDomains();
  
  var uniquePageCount = uniquePages.length;
  var uniqueWebsites = rootDomains.length;
  var topTenSites = rootDomains.slice(0,10);
  
  self.postMessage({ 'uniquePageCount': uniquePageCount, 'uniqueWebsites': uniqueWebsites, 'totalPageViews':  totalPageViews, 'topTenSites': topTenSites });
  
  // Close the worker if the jobs are all done
  if (data.jobNumber == 2) {
  	self.close();
  }
}, false);


/*
*	Add a domain to the array if it is not already there
*
*	@param	domain	The domain to be added into the array
*/
function addRootDomain(domain, visits) {
	var present = false; // Defines whether the domain is present in the rootDomains array
	
	// Loop through the domains already in the array
	for (var i = 0; i < rootDomains.length; i++) {
		// If the domain is already present
		if (rootDomains[i][0] == domain) {
			// Set the present variable to try
			present = true;
			rootDomains[i][1] += visits;
			
			// Break out of the loop
			break;
		}
	}
	
	// If the domain is not present push it to the rootDomains array
	if (present == false) {
		rootDomains.push([domain,visits]);
	}
}

/*
*	Add a url to the uniquePages array if it is not already present.
*
*	@param	url		The url that you wish to add to the array
*/
function addUniquePage(url) {
	var present = false;
	
	for (var i = 0; i < uniquePages.length; i++) {
		if (uniquePages[i] == url) {
			present = true;
			break;
		}
	}
	
	if (present == false) {
		uniquePages.push(url);
	}
}


/*
*	
*/
function sortRootDomains() {
	var unsorted = rootDomains;
	var sorted = [];
	var temp = unsorted;
	var count = 0;
	var trips = unsorted.length;
	
	// Loop through each site
	while (count < trips) {
		var currentHighest = 0;
		var position = 0;
	
		for (var i = 0; i < temp.length; i++) {
			var url = temp[i][0];
			var visits = temp[i][1];
	
			// If this is the highest element update the counter
			if (visits >= currentHighest) {
		
				currentHighest = visits;
				position = i;
		
			}
	
		}
		
		sorted.push(temp[position]);
		temp.splice(position,1);
		
		count++;
	}
	
	rootDomains = sorted;
}


/*
*	Get the base url from a url string
*
*	@param	url			The full url which you wish to process
*	@retrn	baseURL	The base url that has been extracted from the given url.
*/
function getBaseURL(url) {
  var baseURL = url.substring(0, url.indexOf('/', 14));
	
	return baseURL;
}
